package com.hliushi.netty.c3;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author llhuang10
 * @date 2021/10/19 20:14
 */
@Slf4j
public class TaskNettyFuture {

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        EventLoop eventLoop = group.next();

        Future<Integer> future = eventLoop.submit(() -> {
            log.debug("执行计算");
            try {
                Thread.sleep(1000);
                return 50;
            } catch (InterruptedException e) {
                e.printStackTrace();
                return -1;
            }
        });

        // 3.主线程通过future来获取结果
        // log.debug("main线程阻塞等待Future线程的结果");
        // log.debug("Future线程的结果是 {}", future.get());  // future.get() 同步阻塞
        log.debug("Future线程的结果是 {}", future.getNow());
        future.addListener(new GenericFutureListener<Future<? super Integer>>() {
            @Override
            public void operationComplete(Future<? super Integer> future) throws Exception {
                log.debug("结果是 {}", future.getNow());  // future.getNow() 获取任务结果, 非阻塞, 还未产生结果时返回null
            }
        });
        log.debug("main线程非阻塞方式, 获得Future线程的结果, 如果Future没有完成计算, 则返回null");
        // log.debug("Future线程的结果是 {}", future.get());
        log.debug("Future线程的结果是 {}", future.get(500, TimeUnit.MILLISECONDS));


    }
}
